<style scoped lang="scss">
.table12w3 {
  border-top: 1px solid #ddd;

  thead tr {
    border-top: 1px solid #222;
    border-left: 1px solid #222;
  }

  thead tr td {
    background: #e0dfdf;
    border-right: 1px solid #222;
    border-bottom: 1px solid #222;
  }

  tr td {
    border-right: 1px solid #ddd;
    border-bottom: 1px solid #ddd;
    padding: 5px;
  }
}

.overflow2 {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
<template>
  <div>
    <h1>数据库操作系统
      <el-button type="text" @click="()=>triggernewtab()" style="font-size: 12px;padding:0px;">新开tabs</el-button>
    </h1>
    <div>
      <div>
        Data Source: {{ datasource_index }}
        <el-select
            size="mini"
            v-model="datasource_index"
        >
          <el-option v-for="(item,index) in datasourceoptions"
                     :key="index"
                     :label="`${item&&item.database}`"
                     :value="`${item&&item.id}`"
          >
            {{ item.database }}
          </el-option>
        </el-select>
        <div style="margin-left: 5px;display: inline-block;">
          <el-button @click.stop="()=>trigersearchTableName()" size="small">搜索表名称</el-button>
          <el-button size="small" @click="()=>triggerSeeTableDescriptiuon()">表描述</el-button>
        </div>

      </div>
      <el-form :form="queryParams" label-width="auto"
               :inline="true"
               @submit.native.prevent
      >
        <el-form-item>
          <el-autocomplete style="width:420px;"
                           size="small"
                           auto-complete="off"
                           placeholder="表名称"
                           v-model.trim="queryParams.tableName"
                           clearable
                           :fetch-suggestions="triggerliketablename"
                           @keydown.enter.prevent.native="()=>{
                               keys=[]
                           keyswithadata=[]
                           getInfoList()
                           }"
                           @select="()=>{
                        keys=[]
             keyswithadata=[]
             getInfoList()
                     }"
          />
        </el-form-item>
        <el-form-item>
          <div style="margin-left: 10px;">
            <el-button size="small" type="primary" @click="triggersearch">搜索</el-button>
            <el-button type="text" style="padding: 0px" @click="()=>triggerkeys(keys)">过滤表头</el-button>
            <el-button type="text" style="padding: 0px" @click="()=>triggerAddOneRow(keys)">新增row</el-button>
            <el-button type="text" style="padding: 0px" @click="()=>{
             keys=[]
             keyswithadata=[]
             getInfoList()
            }">clear keys
            </el-button>
          </div>

        </el-form-item>
      </el-form>

      <div style="margin-top:10px;display:flex;">
        <div v-for="key in keys">
          <el-input style="width:120px;margin-right:5px;"
                    :placeholder="key" clearable size="mini"
                    v-model.trim="queryParams.queryForm[key]"
          />
        </div>
      </div>

    </div>
    <section style="margin-top: 10px;">
      <table class="table12w3">
        <thead>
        <tr>
          <td width="88">
            <el-button type="text" style="padding: 0px" @click="()=>triggerkeys(keys)">过滤表头</el-button>
          </td>
          <td v-for="key in keys" style="padding:5px;min-width: 66px"
          >
            <span style="padding-right: 5px;"> {{ key }}</span>
            <svg-icon icon-class="eye-open" style="cursor: pointer;" @click.native="()=>{
            triggerSeeKeyDescriptiuon(key)
           }"></svg-icon>
          </td>
        </tr>

        </thead>
        <tbody v-loading="loading">
        <tr v-for="(rowitem,index) in dataList" :key="`${queryParams?.tableName}_${index}`">
          <td></td>
          <td v-for="keyitem in keyswithadata" :key="`${keyitem?.key}_rowindex${index}`">
            <input type="text" style="width: 88px;"
                   v-if="keyitem?.isedit"
                   :value="computed_value(rowitem, keyitem?.key)"
                   @blur="e=>{
                   var _value=e.target?.value;
                   var oldvalue=computed_value(rowitem, keyitem?.key);
                   if(_value==oldvalue){
                    return false
                   }
                   keyitem.isedit=false
                   updatekeyvalue(keyitem,_value,rowitem)

                }"
            />
            <el-tooltip
                v-else
                class="item" effect="dark" :content="computed_value(rowitem, keyitem?.key)" placement="top-start">
              <div class="overflow2" style="max-width: 250px;min-height: 30px;"
                   @dblclick="e=>{
                     if(keyitem?.key?.toLowerCase()=='id'){
                     //id 不能修改
                      return false
                     }
                   keyitem.isedit=true
                  }"
              >
                <div> {{ computed_value(rowitem, keyitem?.key) }}
                </div>
              </div>
            </el-tooltip>

          </td>
        </tr>

        </tbody>

      </table>

      <el-pagination
          :background="true"
          style="padding: 20px;"
          :current-page.sync="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          layout="prev, pager, next"
          :total="total"
          @size-change="(pageSize)=>{$data.queryParams.pageSize=pageSize;dataList=[];getInfoList();}"
          @current-change="(pageNum)=>{$data.queryParams.pageNum=pageNum;dataList=[];getInfoList();}"
      >
      </el-pagination>
    </section>
  </div>
</template>
<script>
import keysformCom from '@/views/databaseui/modify/keysform.vue';
import '@base/mydialogplus/dist/style.css';
import FormDialog from '@base/mydialogplus';
import axios from 'axios';
import * as lodash from 'lodash-es';
import { alertFail, alertWithPayload, safeParseJson } from '@base/utils';
import svgIcon from '@base/svg-icon';
import { openLayer } from '@/utils/layerdialog/layerdialog';

export default {
  data() {
    return {
      datasource_index: `${sessionStorage.getItem('datasource_index') || 1}`,
      datasourceoptions: [],
      queryParams: {
        queryForm: {},
        tableName: sessionStorage.getItem('queryParams.tableName') || '',
      },
      dataList: [],
      keys: [],
      keyswithadata: [],
      total: 0,
      loading: false,
    };
  },
  components: {
    svgIcon,
  },
  mounted() {
    this.initdatabaseouce();
    document.addEventListener('keydown', (event) => {
      console.log('=>(index.vue:202) event',
          event, event?.shiftKey,
          event?.ctrlKey,
          event.key,
      );
      if (event.ctrlKey && event.shiftKey && event.key?.toLocaleLowerCase() === 'p') {
        event.preventDefault();
        this.ctrlShiftPevent();
      }
      if (event.ctrlKey && event.shiftKey && event.key?.toLocaleLowerCase() === 'o') {
        event.preventDefault();
        this.ctrlShiftoevent();
      }
    });
  },
  methods: {
    async ctrlShiftPevent() {
      var datasourceDto = lodash.find(this.datasourceoptions, item => item?.id == this.datasource_index);
      if (!datasourceDto && datasourceDto.id) {
        alertFail('请选择datasource');
        return false;
      }
      var result = await openLayer({
        top: '100px',
        width: '555px',
        title: '搜索表字段',
        data() {
          return {
            datasourceDto,
          };
        },

        components: {
          modify: () => import('@/views/databaseui/layer/dialogTableKeys.vue'),
        },
      });
    },
    //查看表名称
    async ctrlShiftoevent() {
      var datasourceDto = lodash.find(this.datasourceoptions, item => item?.id == this.datasource_index);
      if (!datasourceDto && datasourceDto.id) {
        alertFail('请选择datasource');
        return false;
      }
      var result = await openLayer({
        top: '100px',
        width: '555px',
        title: '搜索表名称',
        data() {
          return { datasourceDto };
        },

        components: {
          modify: () => import('@/views/databaseui/layer/dialogTableName.vue'),
        },
      });

    },

    async initdatabaseouce() {
      var redsult = await axios.get('/api/databaseui/getdatasourceoptions').then(res => res.data);
      console.log('-> redsult', redsult);
      this.datasourceoptions = redsult && redsult.data;
    },
    computed_value(rowitem, key) {
      return rowitem[key];
    },
    async getInfoList() {
      var datasourceDto = lodash.find(this.datasourceoptions, item => item?.id == this.datasource_index);
      if (!datasourceDto && datasourceDto.id) {
        alertFail('请选择datasource');
        return false;
      }

      this.loading = true;
      var queryParmas = this.queryParams?.queryForm;
      queryParmas && (queryParmas['del_state'] = 1);
      var result = await axios.post(`/api/databaseui/getlist`, {
        ...this.queryParams,
        queryForm: queryParmas,
        tableName: this.queryParams?.tableName,
        datasourceDto: datasourceDto,
      }).then(res => res.data);
      this.loading = false;
      if (!(result && result.success)) {
        this.keys = [];
        this.keyswithadata = [];
        this.dataList = [];
        this.queryParams.queryForm = {};
        alertFail(result?.message);
        return false;
      }

      console.log('-> result', result);
      this.dataList = result && result.data || [];

      //开始获取keys
      var keys_res = await axios.post('/api/databaseui/tableproperty', {
        datasourceDto,
        tableName: this.queryParams?.tableName,
      }).then(res => res.data);
      var _keys = (keys_res && keys_res.data || []).map(item => item.Field);

      var _keysfromsession = safeParseJson(sessionStorage.getItem(`queryParams.${this.queryParams?.tableName}.keys`)) || [];

      if (lodash.isEmpty(this.keys)) {
        this.keys = _keysfromsession;
        if (lodash.isEmpty(this.keys)) {
          this.keys = _keys;

        }
      }

      this.keyswithadata = this.keys?.map(key => {
        return {
          key: key,
          isedit: false,
        };
      });
      this.total = result && result.total || 0;
      console.log('-> this.total', this.total);
      console.log('-> this.keys', this.keys);
    },

    async triggersearch() {
      sessionStorage.setItem('datasource_index', this.datasource_index);
      sessionStorage.setItem('queryParams.tableName', this.queryParams?.tableName);


      this.getInfoList();

    },
    trigersearchTableName() {
      axios.get('/api/start_node_fuzzsysystem');

      layer.open({
        type: 2,
        title: '表名称查询',
        shadeClose: true,
        shade: false,
        maxmin: true, //开启最大化最小化按钮
        area: ['620px', '620px'],
        // content: 'http://localhost:18011/',
        content: 'http://localhost:18011/',
      });
    },
    triggernewtab() {
      layer.open({
        type: 2,
        title: '新开',
        shadeClose: true,
        shade: false,
        maxmin: true, //开启最大化最小化按钮
        area: ['620px', '620px'],
        content: '/databaseui',
      });
    },
    async triggerkeys(keys) {
      var result = await FormDialog({
        title: `标题过滤`,
        data() {
          return { keys: lodash.cloneDeep(keys) };
        },
        components: {
          modify: keysformCom,
        },
      });
      var _keys = result && result.data || [];
      this.keys = _keys;
      sessionStorage.setItem(`queryParams.${this.queryParams?.tableName}.keys`, JSON.stringify(_keys));
      this.keyswithadata = this.keys?.map(key => {
        return {
          key: key,
          isedit: false,
        };
      });
    },
    async triggerSeeTableDescriptiuon() {
      var datasourceDto = lodash.find(this.datasourceoptions, item => item?.id == this.datasource_index);
      if (!datasourceDto && datasourceDto.id) {
        alertFail('请选择datasource');
        return false;
      }
      if (!this.queryParams?.tableName) {
        alertFail('请输入表明');
        return false;
      }
      var list_res = await axios.post('/api/databaseui/tableproperty', {
        datasourceDto,
        tableName: this.queryParams?.tableName,
      }).then(res => res.data);
      var list = list_res && list_res.data || [];
      console.log('-> 【triggerSeeTableDescriptiuon】 list', list);
      await FormDialog({
        title: '查看表描述',
        width: '520px',
        data() {
          return { tablelist: list };
        },

        components: {
          modify: () => import('@/views/databaseui/modify/tabledescription.vue'),
        },
      });
    },
    async triggerSeeKeyDescriptiuon(key) {
      var datasourceDto = lodash.find(this.datasourceoptions, item => item?.id == this.datasource_index);
      if (!datasourceDto && datasourceDto.id) {
        alertFail('请选择datasource');
        return false;
      }
      var list_res = await axios.post('/api/databaseui/tableproperty', {
        datasourceDto,
        tableName: this.queryParams?.tableName,
      }).then(res => res.data);
      var list = list_res && list_res.data || [];
      var _one = lodash.find(list, item => item?.Field == key);
      console.log('-> _one', _one);
      layer.confirm(`【${_one?.Field}】字典描述\n\n
       ${_one?.Comment}
      `, {
        shade: false,
        btn: ['确定', '取消'], //按钮
      }, function () {

      }, function () {

      });
    },
    async updatekeyvalue(keyitem, value, rowitem) {
      var datasourceDto = lodash.find(this.datasourceoptions, item => item?.id == this.datasource_index);
      if (!datasourceDto && datasourceDto.id) {
        alertFail('请选择datasource');
        return false;
      }
      var result = await axios.post('/api/databaseui/uppdatekeyvalue', {
        datasourceDto,
        tableproperty: keyitem?.key,
        keyvalue: value,
        mainId: rowitem?.id,
        tableName: this.queryParams?.tableName,
      });
      alertWithPayload(result);

      rowitem[keyitem?.key] = value;

    },
    /**
     * @description: 新增数据 使用mock生成 填充一些内容
     * @params
     * @return
     */
    async triggerAddOneRow() {
      var self = this;
      var datasourceDto = lodash.find(this.datasourceoptions, item => item?.id == this.datasource_index);
      if (!datasourceDto && datasourceDto.id) {
        alertFail('请选择datasource');
        return false;
      }

      var result = await FormDialog({
        title: '新增数据',
        width: '666px',
        data() {
          return {
            tableName: self.queryParams?.tableName,
            datasourceDto,
          };
        },

        components: {
          modify: () => import('@/views/databaseui/modify/addModifyForm.vue'),
        },
      });

      if (!result && result.success) {
        return false;
      }
      var _form = result && result.data || [];


      var result2 = await axios.post('/api/databaseui/addrow', {
        datasourceDto,
        rowData: _form,
        tableName: this.queryParams?.tableName,
      });
      alertWithPayload(result2);
      if (result2 && result2.success) {
        this.getInfoList();
      }
    },
    async triggerliketablename(str, cb) {
      console.log('-> str', str);
      var datasourceDto = lodash.find(this.datasourceoptions, item => item?.id == this.datasource_index);
      if (!datasourceDto && datasourceDto.id) {
        alertFail('请选择datasource');
        return false;
      }
      var redsult = await axios.post('/api/databaseui/gettablenames', {
        datasourceDto,
        tableName: str,
      }).then(res => res.data);
      var list = (redsult && redsult.data || []).map(key => {
        return { value: key };
      });
      //console.log("-> list", list);
      cb(list);

    },

  },
};
</script>
